const express = require('express');
const router = express.Router();
// let db = require("../mysql/db")
const menuapiInfo = require('../source/baseInfo');
const { parentPort } = require('worker_threads');
const { flatArrayToTree } = require('../utils/totree');


/**
 * POST /api/v1/saveMenuapi
 * @summary 添加菜单
 * @description 添加菜单
 * @tags [菜单管理]
 * @produces application/json
 * @param {object} request.body.required - 菜单信息
 * @return {object} 201 - 添加菜单ok
 * @example request - 示例请求
 * {
 *    "name": "首页",
 *    "path": "sundandan",
 *    "mate": "{}",
 *    "icon": 13240981227,
 *    "parentId": 0
 * }
 * @example response - 示例响应
 * {
 *   "data": 'ok'
 * }
 * @consumes application/json
 * @return {array<object>} 200 - 成功添加菜单
 */
router.post('/api/v1/saveMenuapi', async (req, res, next) => {
  const { id, name, path:routerPath, mate,icon, parentId } = req.body;
  const fs = require('fs');
  const path = require('path'); //引入路径
  if(!(name&&routerPath&& mate&&icon &&(parentId===0 ||parentId))){
    res.json({ code: 202, data: [], message: '数据错误,参数有问题' });
  }else{
    let errortext=''
    try {
      const data = fs.readFileSync(path.join(__dirname, '../source/menuapi.json'), 'utf8');
      // 解析JSON数据
      const jsonData = JSON.parse(data);
      const lastItem = jsonData.slice(-1)[0];
      const newdata = { id: (lastItem.id-0) + 1,  name, path:routerPath, mate,icon, parentId  };
      try {
        const data1 = fs.writeFileSync(path.join(__dirname, '../source/menuapi.json'), JSON.stringify([...jsonData,newdata]));
        console.log('已写入');
      } catch (error) {
        res.json({ code: 200, data: [], message: errortext?errortext:'数据获取成功' });
      }
      
      
    } catch (err) {
      console.log(err)
      res.json({ code: 201, data: [], message: '数据错误,接口问题' });
    }
  }
 
  next();
});
/**
 * POST /api/v1/editMenuapiById
 * @summary 编辑菜单
 * @description 编辑菜单
 * @tags [菜单管理]
 * @produces application/json
 * @param {object} request.body.required - id
 * @return {object} 201 - 成功获取
 * @example request - 示例请求
 * {
 *    "id": 1,
 *    "name": "首页",
 *    "path": "sundandan",
 *    "mate": "{}",
 *    "icon": 13240981227,
 *    "parentId": 0
 * }
 * @example response - 示例响应
 * {
 *  data: 'ok'
 * }
 * @return {object} 201 - 异常
 * @consumes application/json
 * @return {object} 200 - 成功获取菜单
 */
router.post('/api/v1/editMenuapiById', async (req, res, next) => {
  const { id,  name, path:routerPath, mate,icon, parentId  } = req.body;
  const fs = require('fs');
  const path = require('path'); //引入路径
  try {
    const data = fs.readFileSync(path.join(__dirname, '../source/menuapi.json'), 'utf8');
    // 解析JSON数据
    const jsonData = JSON.parse(data);
    const filterData = jsonData.filter((exp) => {
      return exp.id !== id;
    });

    let editData = jsonData.filter((exp) => {
      return exp.id === id;
    });
    if(filterData.length === jsonData.length-1 ){

      editData = [
        ...filterData,
        { id, name, path:routerPath, mate,icon, parentId   }
      ]

      try {
        const data1 = fs.writeFileSync(path.join(__dirname, '../source/menuapi.json'), JSON.stringify(editData));
        console.log('已写入');
        res.json({ code: 200, data: 'ok', message: '数据编辑成功' });
      } catch (error) {
        res.json({ code: 201, data: 'error', message: '数据错误,接口问题' });
      }
    }else{
      res.json({ code: 201, data: 'error', message: 'id数据不存在' });
    }
   
   
  } catch (err) {
    res.json({ code: 201, data: 'error', message: '数据错误,接口问题' });
  }
  next();
});


/**
 * POST /api/v1/delMenuapiById
 * @summary 删除菜单
 * @description 删除菜单
 * @tags [菜单管理]
 * @produces application/json
 * @param {object} request.body.required - Menuapiid
 * @return {object} 201 - 成功获取Menuapi
 * @example request - 示例请求
 * {
 *   "id": 1
 * }
 * @example response - 示例响应
 * {
 *  data: 'ok'
 * }
 * @return {object} 201 - 异常
 * @consumes application/json
 * @return {object} 200 - 成功获取菜单
 */
router.post('/api/v1/delMenuapiById', async (req, res, next) => {
  const { id } = req.body;
  const fs = require('fs');
  const path = require('path'); //引入路径
  try {
    const data = fs.readFileSync(path.join(__dirname, '../source/menuapi.json'), 'utf8');
    // 解析JSON数据
    const jsonData = JSON.parse(data);
    const filterData = jsonData.filter((exp) => {
      return exp.id !== id;
    });
    try {
      const data1 = fs.writeFileSync(path.join(__dirname, '../source/menuapi.json'), JSON.stringify(filterData));
      console.log('已写入');
      res.json({ code: 200, data: 'ok', message: '数据获取成功' });
    } catch (error) {
      res.json({ code: 201, data: 'error', message: '数据错误,接口问题' });
    }
  } catch (err) {
    res.json({ code: 201, data: 'error', message: '数据错误,接口问题' });
  }
  next();
});



/**
 * POST /api/v1/getMenuapiListByParent
 * @summary 获取菜单列表
 * @description 获取菜单列表
 * @tags [菜单管理]
 * @produces application/json
 * @example response - 示例响应
 * [
 *   {
 *    "id": 1,
 *    "name": "首页",
 *    "path": "sundandan",
 *    "mate": "{}",
 *    "icon": 13240981227,
 *    "parentId": 0
 *  },
 *  {
 *    "id": 1,
 *    "name": "首页",
 *    "path": "sundandan",
 *    "mate": "{}",
 *    "icon": 13240981227,
 *    "parentId": 0
 *  }
 * ]
 * @return {object} 201 - 异常
 * @consumes application/json
 * @return {object} 200 - 成功获取菜单
 */
router.post('/api/v1/getMenuapiListByParent', async (req, res, next) => {
  const fs = require('fs');
  const { id,parentId } = req.body;

  const path = require('path'); //引入路径
  try {
    const data = fs.readFileSync(path.join(__dirname, '../source/menuapi.json'), 'utf8');
    // 解析JSON数据
    const jsonData = JSON.parse(data);
    const filterData = jsonData.filter((exp) => {
      return exp.parentId !== parentId;
    });

    res.json({ code: 200, data: filterData, message: '数据获取成功' });
  } catch (err) {
    res.json({ code: 201, data: [], message: '数据错误,接口问题' });
  }
  next();
});

/**
 * POST /api/v1/getMenuapiListAll
 * @summary 获取菜单列表
 * @description 获取菜单列表
 * @tags [菜单管理]
 * @produces application/json
 * @example response - 示例响应
 * [
 *   {
 *    "id": 1,
 *    "name": "首页",
 *    "path": "sundandan",
 *    "mate": "{}",
 *    "icon": 13240981227,
 *    "parentId": 0,
 *     "children":[]
 *  },
 *  {
 *    "id": 1,
 *    "name": "首页",
 *    "path": "sundandan",
 *    "mate": "{}",
 *    "icon": 13240981227,
 *    "parentId": 0,
 *     "children":[]
 *  }
 * ]
 * @return {object} 201 - 异常
 * @consumes application/json
 * @return {object} 200 - 成功获取菜单
 */
router.post('/api/v1/getMenuapiListAll', async (req, res, next) => {
  const fs = require('fs');
  const { id,parentId } = req.body;

  const path = require('path'); //引入路径
  try {
    const data = fs.readFileSync(path.join(__dirname, '../source/menuapi.json'), 'utf8');
    // 解析JSON数据
    const jsonData = JSON.parse(data);
    // const filterData = jsonData.filter((exp) => {
    //   return exp.parentId !== parentId;
    // });

    res.json({ code: 200, data: flatArrayToTree(jsonData), message: '数据获取成功' });
  } catch (err) {
    res.json({ code: 201, data: [], message: '数据错误,接口问题' });
  }
  next();
});


module.exports = router;
